/**
 * 转化为树状结构
 */

interface Options {
  primaryKey: string; // 关键key，默认id
  parentKey: string; // 父节点关联的key，默认pid
  startPid: number | string; // 初始状态父节点关联的值，默认0
  childKey: string; // 子节点对应的key，默认children
}

const listToTree = (list: any[], startPid: number | string, opt: Options) => {
  const child: {
    id: string | number;
    label: string | number;
    checked?: boolean;
    [attr: string]: any;
  }[] = [];
  for (const index in list) {
    // 筛查符合条件的数据（主键 = startPid）
    const item = list[index];
    if (
      typeof item[opt.parentKey] !== 'undefined' &&
      item[opt.parentKey] === startPid
    ) {
      // 满足条件则递归
      const nextChild = listToTree(list, item[opt.primaryKey], opt);
      // 节点信息保存
      const node = {
        ...item
      };
      if (nextChild.length > 0) {
        node[opt.childKey] = nextChild;
      }

      child.push(node);
    }
  }
  return child;
};
const formatTree = (list: any[], opt: Partial<Options> = {}) => {
  opt.primaryKey = opt.primaryKey ? opt.primaryKey : 'id';
  opt.parentKey = opt.parentKey ? opt.parentKey : 'pid';
  opt.startPid = opt.startPid ? opt.startPid : 0;
  opt.childKey = opt.childKey ? opt.childKey : 'children';
  return listToTree(list, opt.startPid, opt as Options);
};
export default formatTree;
